import React, { useState, useEffect } from 'react';
import { Upload, Modal } from 'antd';
import 'antd/es/modal/style';
import 'antd/es/slider/style';
import { downloadID, queryByIdFile } from '@/services/file';
import { downloadFileFromResponse } from '@/utils/request';
interface file {
  [file: string]: string | number | any;
}

interface UploadProps {
  limit?: number;
  value?: string;
  onChange?: any;
  fileLists?: file[];
  type?: boolean;
  render?: React.ReactNode;
  disabled?: boolean;
}

interface FileObj {
  url?: string;
  name?: string;
}

/**
 * 根据接口返回的文件数据组装一个上传组件需要的文件数据
 * @param respObj 上传成功返回类型，格式：{id:"xxx", name:"xxx", type:"pdf", url:"xxx" }
 * @param uploadedObj 上传组件需要的文件数据，如果该值为空则创建一个新的
 * @returns {{}}
 */
function makeupUploadedObjByResponseObj(respObj: file, uploadedObj = null) {
  const obj: file = uploadedObj ?? { uid: respObj.id };
  obj.id = respObj.id;
  obj.name = respObj.name;
  // obj.url = getdownLoadUrl(respObj.id);
  obj.type = respObj.type;
  // obj.thumbUrl = getdownLoadUrl(respObj.id);
  obj.status = 'done';
  obj.response = {
    data: [respObj],
  };
  obj.made = 1; // 是否是组装好的数据
  return obj;
}

/**
 * 获取服务端传递回来的的id
 * @param response
 */
function getId(response: file) {
  return response?.response?.data?.[0]?.id;
}

const UplodFile: React.FC<UploadProps> = props => {
  const [fileList, setFileList] = useState<file[]>([]);
  const [fileObj, setFileObj] = useState<FileObj>({});
  const { value, type, render, disabled } = props;

  /**
   * 文件改变
   * @param fileList
   */
  const onChange = ({ fileList: newFileList }: any) => {
    props?.onChange(
      newFileList?.length
        ? newFileList.map((el, index) => ({
            key: index + 1,
            value: getId(el),
          }))
        : '',
    );
    setFileList(newFileList);
  };

  /**
   * 监听文件改变
   */
  // thinking： value 作为 string 或者 [{key,value}] 形式作为多个图片逻辑处理
  // 通过props.onChange 来处理 删除的参数或者其他问题
  useEffect(() => {
    if (value && Array.isArray(value) && value.every(el => el.value)) {
      // 获取文件;
      let arr: any = [];
      value.forEach(element => {
        arr.push(
          new Promise((resolve, reject) => {
            if (element) {
              queryByIdFile({ id: element.value }).then(res => {
                if (res?.responseCode == 200) {
                  resolve(res?.data);
                } else {
                  reject({});
                }
              });
            }
          }),
        );
      });

      Promise.all(arr).then(res => {
        let arrl: any = [];
        res?.forEach((el: any) => {
          if (el) {
            arrl.push(makeupUploadedObjByResponseObj(el));
          }
        });
        setFileList(arrl);
      });
    }
  }, [value]);

  /**
   * 文件删除
   * @param file
   */
  const onRemove = async file => {
    try {
      await new Promise((resolve, reject) => {
        resolve();
      });
    } catch {
      return false;
    }
  };

  const onDownload = (file: any) => {
    downloadID(getId(file)).then((res: any) => downloadFileFromResponse(res));
  };

  let defaultProps: any = {
    action: '/sealCuttingApi/file/uploadFile',
    listType: 'picture-card',
    fileList,
    onChange,
    onRemove,
    onDownload,
    disabled,
    showUploadList: {
      showPreviewIcon: false,
      showDownloadIcon: true,
    },
  };

  return (
    <div>
      <Upload {...defaultProps}>{fileList.length < 100 && (render || '+ Upload')}</Upload>
    </div>
  );
};

export default UplodFile;
